import { Button, DatePicker, Popconfirm, Modal, Table, Tag, Form, Input, message } from "antd"
import React from 'react'
import { getTaskList, addTask, removeTask, completeTask } from '../api/index'
import './Task.scss'

//对日期处理的方法
const zero = (text) => {
    return text.length < 2 ? text = '0' + text : text
}
const formatTime = (time) => {
    let [, month, day, hours = '00', minutes = '00'] = time.match(/\d+/g);
    return `${zero(month)}-${zero(day)} ${zero(hours)}:${zero(minutes)}`
}
class Task extends React.Component {
    //定义表格列的数据
    columns = [
        {
            title: '编号',
            dataIndex: 'id',
            width: '8%'
        },
        {
            title: '任务描述',
            dataIndex: 'task',
            ellipsis: true,
            width: '50%'
        },
        {
            title: '状态',
            dataIndex: 'state',
            align: 'center',
            width: '10%',
            render: text => +text === 2 ? '完成' : '未完成'
        },
        {
            title: '完成时间',
            dataIndex: 'time',
            align: 'center',
            width: '15%',
            render: (_, record) => {
                let { state, time, complete } = record
                if (+state === 1) {
                    return formatTime(complete)
                } else {
                    return formatTime(time)
                }
            }
        },
        {
            title: '操作',
            render: (_, record) => {
                let { id, state } = record
                return <>
                    <Popconfirm title="您确定要删除此任务吗？" onConfirm={() => { this.handleRemove(id) }}>
                        <Button type="link">删除</Button>
                    </Popconfirm>
                    {+state === 1 ? <Popconfirm title="您确定把此任务设置成完成吗？" onConfirm={() => { this.handleUpdate(id) }}>
                        <Button type="link">完成</Button>
                    </Popconfirm> : null}

                </>
            }
        },
    ];
    //初始化组件状态
    state = {
        tableData: [
            {
                id: 1,
                task: '今天天气很不错，今天阳光明媚',
                state: 1,
                time: '2022-1-29 18:00:00',
                complete: '2022-1-29 18:00:00'
            },
            {
                id: 2,
                task: '今天天气很不错，今天阳光明媚',
                state: 2,
                time: '2022-11-29 9:00:00',
                complete: '2022-11-9 18:00:00'
            }
        ],
        tableLoading: false,
        modalVisible: false,
        confirmLoading: false,
        selectedIndex: 0
    }
    /* 对话框和表单处理 */
    //关闭对话框 & 清除表单中的内容
    closeModal = () => {
        this.setState({
            modalVisible: false,
            confirmLoading: false
        })
        this.formIns.resetFields();
    }
    //新增任务
    submit = async () => {
        try {
            this.setState({
                confirmLoading: true
            })
            //表单验证
            await this.formIns.validateFields();
            //获取form收集的信息
            let { task, time } = this.formIns.getFieldValue();
            time = time.format('YYYY-MM-DD HH:mm:ss')
            //向服务器发送请求
            let { code } = await addTask(task, time);
            if (+code !== 0) {
                message.error('很遗憾当前操作失败，请稍后再试')
            } else {
                this.closeModal()
                this.queryData();
                message.success('恭喜你，当前操作成功！')
            }
        } catch (_) { }
        this.setState({
            confirmLoading: false
        })
    }
    /* 关于table数据的处理 */
    // 从服务器获取指定状态的任务
    queryData = async () => {
        let { selectedIndex } = this.state;
        try {
            this.setState({
                tableLoading: true
            })
            let { code, list } = await getTaskList(selectedIndex);
            if (+code !== 0) list = []
            this.setState({
                tableData: list
            })
        } catch (_) { }
        this.setState({
            tableLoading: false
        })

    }

    //删除
    handleRemove = async (id) => {
        try {
            let { code } = await removeTask(id);
            if (+code !== 0) {
                message.error('很遗憾当前操作失败，请稍后再试')
            } else {
                this.queryData();
                message.success('恭喜你，当前操作成功！')
            }
        } catch (_) { }
    }
    //完成
    handleUpdate = async (id) => {
        try {
            let { code } = await completeTask(id);
            if (+code !== 0) {
                message.error('很遗憾当前操作失败，请稍后再试')
            } else {
                this.queryData();
                message.success('恭喜你，当前操作成功！')
            }
        } catch (_) { }
    }

    // 周期函数
    componentDidMount() {
        //第一次渲染完毕后，立即发送数据请求，获取真实的数据
        this.queryData();
    }
    //选中状态切换
    changeIndex = (index) => {
        if (index === this.selectedIndex) return
        this.setState({
            selectedIndex: index
        }, () => {
            this.queryData();
        })
    }
    render() {
        let { tableData, tableLoading, modalVisible, confirmLoading, selectedIndex } = this.state
        return <div className="task-box">
            {/* 头部 */}
            <div className="header">
                <h2 className="title">TASK OA任务管理系统</h2>
                <Button type="primary" onClick={() => {
                    this.setState({
                        modalVisible: true
                    })
                }}>新增任务</Button>
            </div>
            {/* 标签 */}
            <div className="tag-box">
                {['全部', '未完成', '已完成'].map((item, index) => {
                    return <Tag key={index} onClick={this.changeIndex.bind(null, index)} color={index === selectedIndex ? '#1677ff' : ''}>{item}</Tag>
                })}
                {/*  <Tag color="#1677ff">全部</Tag>
                <Tag>未完成</Tag>
                <Tag>已完成</Tag> */}
            </div>
            {/* 表格 */}
            <Table dataSource={tableData} columns={this.columns} loading={tableLoading} pagination={false} rowKey="id" />
            {/* 
            对话框 & 表单
            open：是否打开新增任务窗口
            confirmLoading ：确认按钮是否加载
            keyboard：是否支持esc关闭
            maskClosable : 点击遮罩层是否关闭
            okText ：按钮文字
            onCancel:点击x号或者点击取消做的事情
            onOk：提交表单数据
            */}
            <Modal title="新增任务窗口" open={modalVisible} confirmLoading={confirmLoading} keyboard={true} maskClosable={false} okText="确认提交" onCancel={this.closeModal} onOk={this.submit}>
                {/* initialValues表单的初始值 
                layout="vertical"改变标题与输入内容的布局，vertical表示纵向布局
                requiredMark标题前面是否加*
                */}
                <Form
                    ref={x => this.formIns = x}
                    layout="vertical"
                    initialValues={{
                        task: '',
                        time: ''
                    }}
                >
                    {/* 
                    label：前面的字 
                    name：收集表单数据的字段
                    validateTrigger=“onBlur”当失去焦点的时候触发校验规则
                    rules规则校验
                    */}
                    <Form.Item label="任务描述" name="task" validateTrigger="onBlur" rules={[
                        { required: true, message: '任务描述是必填的' },
                        { min: 6, message: '输入的内容至少6为及以上' }
                    ]}>
                        <Input.TextArea rows={4} style={{ resize: 'none' }} />
                    </Form.Item>
                    <Form.Item label="预期完成时间" name="time" validateTrigger="onBlur" rules={[
                        { required: true, message: '预期完成时间是必填项' }
                    ]}>
                        <DatePicker showTime />
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    }
}
export default Task